import math

from django.shortcuts import render,HttpResponse
from django.utils.safestring import mark_safe

from django.utils.deprecation import MiddlewareMixin
from app_01.models import *
from django import forms
# Create your views here.

class Login(forms.Form):
    username=forms.CharField(
        label='用户名',
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'autocomplete':"off"
            }
        )
    )
    password = forms.CharField(
        label='密码',

        widget=forms.TextInput(
            attrs={
                'class': 'form-control'
            },
        )
    )
    yanzhengma = forms.CharField(
        label='验证码',

        widget=forms.TextInput(
            attrs={
                'class': 'form-control img'
            },
        )
    )



def home(req):
    print(req.session.get('img_code'))
    if req.method=='GET':
        form =Login()
        return render(req, 'index.html', {'form': form})
    else:
        form=Login(data=req.POST)
        if form.is_valid():
            print(form.cleaned_data['yanzhengma'],req.session['img_code'])
            if form.cleaned_data['yanzhengma']!=req.session['img_code']:
                form.add_error('yanzhengma','验证码有误')
                return render(req, 'index.html', {'form': form})

            # print(form.cleaned_data)
            req.session['aaa']='bbb'
            # print(req.session)
            # if 1:
            #     form.add_error('password','用户名或者密码有误，请重新输入')
            #     return render(req, 'index.html', {'form': form})

        return render(req,'index.html', {'form':form})
    # return render(req,'index.html', {'form':form})
from yanzhengma import  pic
from  io import BytesIO
def yanzhengma(req):
    # print(yanzhengma())
    img,text=pic()
    req.session['img_code']=text
    req.session.set_expiry(60)
    stream=BytesIO()
    img.save(stream,'png')
    return HttpResponse(stream.getvalue(),content_type="image/png")
def list(req):
    s=req.session.get('aa')
    if not s:
    return render(req,'list.html')